/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.connection.parser.json.itemparsers;

import com.google.gjson.JSONException;
import com.google.gjson.JSONObject;
import com.google.gjson.JSONValue;
import com.hercules.android.receiver.connection.parser.CommandParsingException;
import com.hercules.android.receiver.connection.parser.MalformedCommandException;

/**
 * Default parser, it does not change property type.
 * <p>
 * AndroidAssembly2 this class was added in Android Assembly 2
 *
 * @author 7realm
 * @version 1.0
 */
public class DefaultParser extends FieldParser {
    /**
     * Constructor for {@link DefaultParser}.
     *
     * @param required if property is required
     */
    public DefaultParser(boolean required) {
        super(required);
    }

    /**
     * Parses property.
     *
     * @param path the path to value
     * @param json the JSON
     * @param keyName the name of current JSON key
     * @param instance the instance of object, parsed value will be set to it
     * @return the parsed value
     * @throws CommandParsingException if error occurs while parsing
     */
    @Override
    protected Object doParse(StringBuilder path, JSONObject json, String keyName, Object instance)
        throws CommandParsingException {
        try {
            // get value
        	JSONValue result = json.get(keyName);
        	if (null != result.isString()) {
        		return result.isString().stringValue();
        	} else if (null != result.isBoolean()) {
        		return result.isBoolean().booleanValue();
        	} else if (null != result.isNumber()) {
        		return result.isNumber().doubleValue();
        	} else if (null != result.isNull()) {
        		return null;
        	} else {
        		// throw new MalformedCommandException("Not supported default type: " + result.toString());
        		// return result.toString();
        		return result;
        	}
        } catch (JSONException e) {
            // will never occur, because existence is checked before
            throw new MalformedCommandException("Error occurred while parsing string field '" + path
                + "'. JSON: '" + json + "'.", e);
        }
    }

}
